package xyz.wbsite.dbtool.javafx.tool;

import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonBar;
import javafx.scene.control.ButtonType;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressIndicator;
import javafx.scene.control.RadioButton;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.TextInputDialog;
import javafx.scene.control.ToggleGroup;
import javafx.scene.image.Image;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.VBox;
import javafx.stage.DirectoryChooser;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import xyz.wbsite.dbtool.Application;
import xyz.wbsite.dbtool.javafx.JavaFxApplication;
import xyz.wbsite.dbtool.javafx.ctrl.ConnectInfoController;
import xyz.wbsite.dbtool.javafx.ctrl.OptionAndroidController;
import xyz.wbsite.dbtool.javafx.ctrl.OptionApiController;
import xyz.wbsite.dbtool.javafx.ctrl.OptionDocController;
import xyz.wbsite.dbtool.javafx.ctrl.OptionSelectController;
import xyz.wbsite.dbtool.javafx.ctrl.OptionVueController;
import xyz.wbsite.dbtool.javafx.manger.ManagerFactory;
import xyz.wbsite.dbtool.javafx.manger.ProjectManager;
import xyz.wbsite.dbtool.javafx.po.AndroidOption;
import xyz.wbsite.dbtool.javafx.po.Api;
import xyz.wbsite.dbtool.javafx.po.Doc;
import xyz.wbsite.dbtool.javafx.po.Field;
import xyz.wbsite.dbtool.javafx.po.Module;
import xyz.wbsite.dbtool.javafx.po.SelectItem;
import xyz.wbsite.dbtool.javafx.po.VueOption;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Dialog {

    private static Stage popup;

    public static void showTimedDialog(final long time, String message) {
        popup = new Stage();
        popup.setAlwaysOnTop(true);
        popup.initModality(Modality.APPLICATION_MODAL);
        final Button closeBtn = new Button("知道了");
        closeBtn.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                popup.close();
            }
        });

        VBox root = new VBox();
        root.setPadding(new Insets(10));
        root.setAlignment(Pos.BASELINE_CENTER);
        root.setSpacing(10);
        root.getChildren().addAll(new Label(message), closeBtn);
        Scene scene = new Scene(root);
        popup.setScene(scene);
        popup.setTitle("提示信息");
        popup.show();

        Thread thread = new Thread() {
            @Override
            public void run() {
                try {
                    Thread.sleep(time);
                    if (popup.isShowing()) {
                        Platform.runLater(new Runnable() {
                            @Override
                            public void run() {
                                popup.close();
                            }
                        });
                    }
                } catch (Exception exp) {
                    exp.printStackTrace();
                }
            }
        };
        thread.setDaemon(true);
        thread.start();
    }

    public static void showYesNo(String message) {
        showYesNo("提示", message, null);
    }

    public static void showYesNo(String title, String message) {
        showYesNo(title, message, null);
    }

    public static void showYesNo(String title, String message, ConfirmCall call) {
        Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
        Stage stage = (Stage) alert.getDialogPane().getScene().getWindow();
        stage.getIcons().add(new Image(ResourceUtil.getInput("icon.png")));
        alert.setHeaderText(null);
        alert.setTitle(title);
        alert.setContentText(message);
        alert.setX(JavaFxApplication.primaryStage.getX() + JavaFxApplication.primaryStage.getWidth() / 2 - 213);
        alert.setY(JavaFxApplication.primaryStage.getY() + JavaFxApplication.primaryStage.getHeight() / 2 - 70);
        Optional<ButtonType> buttonType = alert.showAndWait();
        if (call != null) {
            if (buttonType.get().getButtonData().equals(ButtonBar.ButtonData.YES)) {
                call.call(true);
            } else {
                call.call(false);
            }
        }
    }

    public static void showError(String message) {
        Platform.runLater(new Runnable() {
            public void run() {
                Alert alert = new Alert(Alert.AlertType.ERROR);
                Stage stage = (Stage) alert.getDialogPane().getScene().getWindow();
                stage.getIcons().add(new Image(ResourceUtil.getInput("icon.png")));
                alert.setTitle("错误");
                alert.setX(JavaFxApplication.primaryStage.getX() + JavaFxApplication.primaryStage.getWidth() / 2 - 213);
                alert.setY(JavaFxApplication.primaryStage.getY() + JavaFxApplication.primaryStage.getHeight() / 2 - 70);
                alert.setHeaderText("");
                alert.setContentText(message);
                alert.show();
            }
        });
    }

    public static void showSuccess(String message) {
        Platform.runLater(new Runnable() {
            public void run() {
                Alert alert = new Alert(Alert.AlertType.INFORMATION);
                Stage stage = (Stage) alert.getDialogPane().getScene().getWindow();
                stage.getIcons().add(new Image(ResourceUtil.getInput("icon.png")));
                alert.setTitle("消息");
                alert.setX(JavaFxApplication.primaryStage.getX() + JavaFxApplication.primaryStage.getWidth() / 2 - 213);
                alert.setY(JavaFxApplication.primaryStage.getY() + JavaFxApplication.primaryStage.getHeight() / 2 - 70);
                alert.setHeaderText("");
                alert.setContentText(message);
                alert.show();
            }
        });
    }

    private static javafx.scene.control.Dialog dialog = null;

    public static void showWait(String message) {
        if (dialog == null) {
            dialog = new javafx.scene.control.Dialog();
            dialog.setTitle("提示");
            Stage stage = (Stage) dialog.getDialogPane().getScene().getWindow();
            stage.getIcons().add(new Image(ResourceUtil.getInput("icon.png")));
            dialog.setResult("1");
            dialog.setX(JavaFxApplication.primaryStage.getX() + JavaFxApplication.primaryStage.getWidth() / 2 - 68);
            dialog.setY(JavaFxApplication.primaryStage.getY() + JavaFxApplication.primaryStage.getHeight() / 2 - 70);

            GridPane gridPane = new GridPane();
            gridPane.setPrefWidth(200);
            gridPane.setHgap(10);
            gridPane.setVgap(10);
            gridPane.setAlignment(Pos.CENTER);
            gridPane.setPadding(new Insets(10, 10, 10, 10));
            dialog.getDialogPane().setContent(gridPane);

            ProgressIndicator indicator = new ProgressIndicator();
            indicator.setPrefSize(30, 30);
            gridPane.add(indicator, 0, 0);
            gridPane.add(new Label(message), 0, 1);
            dialog.show();
        }
    }

    public static void stopWait() {
        if (dialog != null) {
            Platform.runLater(new Runnable() {
                @Override
                public void run() {
                    dialog.close();
                    dialog = null;
                }
            });
        }
    }

    public static void showDirectoryChooser(File file, DirectoryCall call) {
        DirectoryChooser directoryChooser = new DirectoryChooser();
        directoryChooser.setInitialDirectory(file);
        Stage stage = new Stage();
        stage.setX(JavaFxApplication.primaryStage.getX());
        stage.setY(JavaFxApplication.primaryStage.getY());
        File file_ = directoryChooser.showDialog(stage);

        if (file_ != null && call != null) {
            call.call(file_);
        }
    }

    public static void showDBConnectInput() {
        Stage stage = new Stage();
        stage.setAlwaysOnTop(true);
        stage.initModality(Modality.APPLICATION_MODAL);

        FXMLLoader dbdetailloader = new FXMLLoader(Application.class.getResource("../../../fxml/connectInfo.fxml"));
        try {
            dbdetailloader.load();
            Parent root = dbdetailloader.getRoot();
            Scene scene = new Scene(root);
            stage.setScene(scene);
            stage.setTitle("连接信息");

            ConnectInfoController controller = dbdetailloader.getController();

            ChoiceBox databaseType = controller.getDatabaseType();
            ObservableList<String> data = FXCollections.observableArrayList();
            data.add("Oracle");
            data.add("Mysql");
            databaseType.setItems(data);
            databaseType.setValue("Mysql");
            controller.getDriver().setText("com.mysql.jdbc.Driver");
            controller.getUrl().setText("jdbc:mysql://127.0.0.1:3306/tableName");

            databaseType.setOnAction(new EventHandler<ActionEvent>() {
                @Override
                public void handle(ActionEvent event) {
                    String value = (String) databaseType.getValue();

                    if ("Oracle".equals(value)) {
                        controller.getDriver().setText("oracle.jdbc.OracleDriver");
                        controller.getUrl().setText("jdbc:oracle:thin:@127.0.0.1:1521:orcl");
                    } else if ("Mysql".equals(value)) {
                        controller.getDriver().setText("com.mysql.jdbc.Driver");
                        controller.getUrl().setText("jdbc:mysql://127.0.0.1:3306/tableName");
                    }
                }
            });

            Button test = controller.getTest();
            test.setOnAction(new EventHandler<ActionEvent>() {
                @Override
                public void handle(ActionEvent event) {
                    String type = (String) controller.getDatabaseType().getValue();
                    String driver = controller.getDriver().getText();
                    String url = controller.getUrl().getText();
                    String userName = controller.getUserName().getText();
                    String password = controller.getPassword().getText();

                    Map<String, String> map = new HashMap<String, String>();
                    map.put("type", type);
                    map.put("url", url);
                    map.put("username", userName);
                    map.put("password", password);
                    map.put("driverClassName", driver);
                    boolean b = ProjectManager.testConnect(map);
                    if (b) {
                        Dialog.showYesNo("连接成功!");
                    } else {
                        Dialog.showYesNo("连接失败!");
                    }
                }
            });
            Button load = controller.getLoad();
            load.setOnAction(new EventHandler<ActionEvent>() {
                @Override
                public void handle(ActionEvent event) {
                    String type = (String) controller.getDatabaseType().getValue();
                    String driver = controller.getDriver().getText();
                    String url = controller.getUrl().getText();
                    String userName = controller.getUserName().getText();
                    String password = controller.getPassword().getText();

                    if (driver == null || driver.equals("")) {
                        Dialog.showYesNo("驱动名称不能为空!");
                        return;
                    } else if (url == null || url.equals("")) {
                        Dialog.showYesNo("连接不能为空!");
                        return;
                    } else if (userName == null || userName.equals("")) {
                        Dialog.showYesNo("用户名不能为空!");
                        return;
                    } else if (password == null || password.equals("")) {
                        Dialog.showYesNo("密码不能为空!");
                        return;
                    }

                    for (Module db : ManagerFactory.getProjectManager().getMds()) {
                        if (db.getName().equals(userName)) {
                            Dialog.showYesNo("已经存的模块!");
                            return;
                        }
                    }

                    Map<String, String> map = new HashMap<String, String>();
                    map.put("type", type);
                    map.put("url", url);
                    map.put("username", userName);
                    map.put("password", password);
                    map.put("driverClassName", driver);

                    Dialog.showWait("加载中,请稍等...");
                    new Thread() {
                        @Override
                        public void run() {
                            if (ProjectManager.loadMD(map)) {
                                Platform.runLater(new Runnable() {
                                    @Override
                                    public void run() {
                                        Dialog.stopWait();
                                        stage.close();
                                    }
                                });
                            }
                        }
                    }.start();
                }
            });
            Button cancel = controller.getCancel();
            cancel.setOnAction(new EventHandler<ActionEvent>() {
                @Override
                public void handle(ActionEvent event) {
                    stage.close();
                }
            });

            stage.show();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void showApi() {
        Stage stage = new Stage();
        stage.initModality(Modality.APPLICATION_MODAL);
        stage.setAlwaysOnTop(false);

        FXMLLoader dbdetailloader = new FXMLLoader(Application.class.getResource("../../../fxml/OptionApi.fxml"));
        try {
            dbdetailloader.load();
            Parent root = dbdetailloader.getRoot();
            Scene scene = new Scene(root);

            stage.setScene(scene);
            stage.setTitle("API生成");

            OptionApiController controller = dbdetailloader.getController();
            TextField modulePath = controller.getModulePath();
            TextField apiPath = controller.getApiPath();
            TableView apis = controller.getApis();

            controller.getSelectModulePath().setOnAction(new EventHandler<ActionEvent>() {
                @Override
                public void handle(ActionEvent event) {
                    Dialog.showDirectoryChooser(null, new Dialog.DirectoryCall() {
                        @Override
                        public void call(File result) {
                            modulePath.setText(result.getAbsolutePath());

                            String projectName = "";
                            // 尝试查找Windows下的项目名称
                            String path = result.getAbsolutePath();
                            String pathReplace = Tool.replaceSeparator(path, "#");
                            Pattern compile = Pattern.compile("#([^#]*)#src#main#java#");
                            Matcher matcher = compile.matcher(pathReplace);
                            if (matcher.find()) {
                                projectName = matcher.group(1);
                            }

                            apiPath.setText(new File(ProjectManager.getPath(), projectName + "-api").getAbsolutePath());
                        }
                    });
                }
            });

            controller.getSelectSdkPath().setOnAction(new EventHandler<ActionEvent>() {
                @Override
                public void handle(ActionEvent event) {
                    Dialog.showDirectoryChooser(null, new Dialog.DirectoryCall() {
                        @Override
                        public void call(File result) {
                            String text = modulePath.getText();
                            File moduleFile = new File(text);

                            apiPath.setText(new File(result.getAbsolutePath(), moduleFile.getName() + "-api").getAbsolutePath());
                            System.out.println(result.getAbsolutePath());
                        }
                    });
                }
            });

            controller.getAll().setOnAction(new EventHandler<ActionEvent>() {
                @Override
                public void handle(ActionEvent event) {
                    check(controller, controller.getAll().isSelected(), "");
                }
            });
            controller.getCreate().setOnAction(new EventHandler<ActionEvent>() {
                @Override
                public void handle(ActionEvent event) {
                    check(controller, controller.getCreate().isSelected(), "create");
                }
            });
            controller.getDelete().setOnAction(new EventHandler<ActionEvent>() {
                @Override
                public void handle(ActionEvent event) {
                    check(controller, controller.getDelete().isSelected(), "delete");
                }
            });
            controller.getUpdate().setOnAction(new EventHandler<ActionEvent>() {
                @Override
                public void handle(ActionEvent event) {
                    check(controller, controller.getUpdate().isSelected(), "update");
                }
            });
            controller.getFind().setOnAction(new EventHandler<ActionEvent>() {
                @Override
                public void handle(ActionEvent event) {
                    check(controller, controller.getFind().isSelected(), "find");
                }
            });
            controller.getSearch().setOnAction(new EventHandler<ActionEvent>() {
                @Override
                public void handle(ActionEvent event) {
                    check(controller, controller.getSearch().isSelected(), "search");
                }
            });
            controller.getGet().setOnAction(new EventHandler<ActionEvent>() {
                @Override
                public void handle(ActionEvent event) {
                    check(controller, controller.getGet().isSelected(), "get");
                }
            });

            apiPath.requestFocus();
            modulePath.textProperty().addListener(new ChangeListener<String>() {
                @Override
                public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
                    if (newValue != null && !"".equals(newValue)){
                        Dialog.showWait("加载中...");
                        Callable<Object> callable = Executors.callable(new Runnable() {
                            @Override
                            public void run() {
                                controller.load();
                                Dialog.stopWait();
                            }
                        });
                        Executors.newSingleThreadExecutor().submit(callable);
                    }
                }
            });


            Button start = controller.getStart();
            start.setOnAction(new EventHandler<ActionEvent>() {
                @Override
                public void handle(ActionEvent event) {
                    String module = controller.getModulePath().getText();
                    String api = controller.getApiPath().getText();

                    if (new File(module).exists()) {
                        Dialog.showWait("生成中...");
                        ProjectManager dBmanger = ManagerFactory.getProjectManager();
                        dBmanger.generateApi(new File(module), new File(api), controller.getDomainList(), controller.getData());
                        Dialog.stopWait();
                        Platform.runLater(new Runnable() {
                            @Override
                            public void run() {
                                stage.close();
                            }
                        });
                    } else {
                        Dialog.showYesNo("项目不存在!");
                    }
                }
            });

            Button cancel = controller.getCancel();
            cancel.setOnAction(new EventHandler<ActionEvent>() {
                @Override
                public void handle(ActionEvent event) {
                    stage.close();
                }
            });

            stage.show();

            // 自动查找目录下的项目
            ProjectManager dBmanger = ManagerFactory.getProjectManager();
            File file = dBmanger.getPath();
            File[] files = file.listFiles();
            s:
            for (File f : files) {
                if (!f.getName().contains(".")) {
                    File modul = findAction(f);
                    if (modul == null) {
                        modulePath.setText("");
                        apiPath.setText("");
                    } else {
                        modulePath.setText(f.getAbsolutePath());
                        apiPath.setText(new File(ProjectManager.getPath(), f.getName() + "-api").getAbsolutePath());
                        break s;
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void showDoc() {
        Stage stage = new Stage();
        stage.initModality(Modality.APPLICATION_MODAL);

        FXMLLoader dbdetailloader = new FXMLLoader(Application.class.getResource("../../../fxml/OptionDoc.fxml"));
        try {
            dbdetailloader.load();
            Parent root = dbdetailloader.getRoot();
            Scene scene = new Scene(root);

            stage.setScene(scene);
            stage.setTitle("Doc生成");

            OptionDocController controller = dbdetailloader.getController();
            TextField modulePath = controller.getModulePath();
            TextField docPath = controller.getDocPath();
            TableView apis = controller.getApis();

            controller.getSelectModulePath().setOnAction(new EventHandler<ActionEvent>() {
                @Override
                public void handle(ActionEvent event) {
                    Dialog.showDirectoryChooser(null, new Dialog.DirectoryCall() {
                        @Override
                        public void call(File result) {
                            modulePath.setText(result.getAbsolutePath());

                            String projectName = "";
                            // 尝试查找Windows下的项目名称
                            String path = result.getAbsolutePath();
                            String pathReplace = Tool.replaceSeparator(path, "#");
                            Pattern compile = Pattern.compile("#([^#]*)#src#main#java#");
                            Matcher matcher = compile.matcher(pathReplace);
                            if (matcher.find()) {
                                projectName = matcher.group(1);
                            }

                            docPath.setText(new File(ProjectManager.getPath(), projectName + "-doc").getAbsolutePath());
                        }
                    });
                }
            });

            controller.getSelectDocPath().setOnAction(new EventHandler<ActionEvent>() {
                @Override
                public void handle(ActionEvent event) {
                    Dialog.showDirectoryChooser(null, new Dialog.DirectoryCall() {
                        @Override
                        public void call(File result) {
                            String text = modulePath.getText();
                            File moduleFile = new File(text);

                            docPath.setText(new File(result.getAbsolutePath(), moduleFile.getName() + "-doc").getAbsolutePath());
                            System.out.println(result.getAbsolutePath());
                        }
                    });
                }
            });

            controller.getAjaxDoc().setOnAction(new EventHandler<ActionEvent>() {
                @Override
                public void handle(ActionEvent event) {
                    List<Doc> data = controller.getData();
                    for (Doc datum : data) {
                        if ("ajax".equals(datum.getType())) {
                            datum.setCheck(controller.getAjaxDoc().isSelected());
                        }
                    }
                }
            });

            controller.getApiDoc().setOnAction(new EventHandler<ActionEvent>() {
                @Override
                public void handle(ActionEvent event) {
                    List<Doc> data = controller.getData();
                    for (Doc datum : data) {
                        if ("api".equals(datum.getType())) {
                            datum.setCheck(controller.getApiDoc().isSelected());
                        }
                    }
                }
            });

            docPath.requestFocus();
            modulePath.textProperty().addListener(new ChangeListener<String>() {
                @Override
                public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
                    Dialog.showWait("加载中...");
                    Callable<Object> callable = Executors.callable(new Runnable() {
                        @Override
                        public void run() {
                            controller.load();
                            Dialog.stopWait();
                        }
                    });
                    Executors.newSingleThreadExecutor().submit(callable);
                }
            });

            Button start = controller.getStart();
            start.setOnAction(new EventHandler<ActionEvent>() {
                @Override
                public void handle(ActionEvent event) {
                    String module = controller.getModulePath().getText();
                    String api = controller.getDocPath().getText();

                    if (new File(module).exists()) {
                        Dialog.showWait("生成中...");
                        ProjectManager dBmanger = ManagerFactory.getProjectManager();
                        dBmanger.generateDoc(new File(module), new File(api), controller.getData());
                        Dialog.stopWait();
                        Platform.runLater(new Runnable() {
                            @Override
                            public void run() {
                                stage.close();
                            }
                        });
                    } else {
                        Dialog.showYesNo("项目不存在!");
                    }
                }
            });

            Button cancel = controller.getCancel();
            cancel.setOnAction(new EventHandler<ActionEvent>() {
                @Override
                public void handle(ActionEvent event) {
                    stage.close();
                }
            });

            stage.show();

            // 自动查找目录下的项目
            ProjectManager dBmanger = ManagerFactory.getProjectManager();
            File file = dBmanger.getPath();
            File[] files = file.listFiles();
            s:
            for (File f : files) {
                if (!f.getName().contains(".")) {
                    File modul = findAction(f);
                    if (modul == null) {
                        modulePath.setText("");
                        docPath.setText("");
                    } else {
                        modulePath.setText(f.getAbsolutePath());
                        docPath.setText(new File(ProjectManager.getPath(), f.getName() + "-doc").getAbsolutePath());
                        break s;
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void showSelectEdit(Field field) {
        Stage stage = new Stage();
        stage.initModality(Modality.APPLICATION_MODAL);

        FXMLLoader dbdetailloader = new FXMLLoader(Application.class.getResource("../../../fxml/OptionSelect.fxml"));
        try {
            dbdetailloader.load();
            Parent root = dbdetailloader.getRoot();
            Scene scene = new Scene(root);

            stage.setScene(scene);
            stage.setTitle("编辑选项");
            stage.setX(JavaFxApplication.primaryStage.getX() + JavaFxApplication.primaryStage.getWidth() / 2 - 150);
            stage.setY(JavaFxApplication.primaryStage.getY() + JavaFxApplication.primaryStage.getHeight() / 2 - 100);

            OptionSelectController controller = dbdetailloader.getController();
            controller.setData(field.getSelectItems());

            Button add = controller.getAdd();
            add.setOnMouseClicked(new EventHandler<MouseEvent>() {
                @Override
                public void handle(MouseEvent event) {
                    SelectItem newSelectItem = controller.getNewSelectItem();
                    controller.getData().add(newSelectItem);
                    controller.refresh();
                }
            });

            Button sub = controller.getSub();
            sub.setOnMouseClicked(new EventHandler<MouseEvent>() {
                @Override
                public void handle(MouseEvent event) {
                    int selectedIndex = controller.getDatas().getSelectionModel().getSelectedIndex();
                    if (selectedIndex > -1) {
                        controller.getData().remove(selectedIndex);
                        controller.getDatas().getSelectionModel().clearSelection();
                        controller.refresh();
                    }
                }
            });

            Button start = controller.getStart();
            start.setOnAction(new EventHandler<ActionEvent>() {
                @Override
                public void handle(ActionEvent event) {
                    Dialog.stopWait();
                    Platform.runLater(new Runnable() {
                        @Override
                        public void run() {
                            stage.close();
                        }
                    });
                }
            });

            Button cancel = controller.getCancel();
            cancel.setOnAction(new EventHandler<ActionEvent>() {
                @Override
                public void handle(ActionEvent event) {
                    stage.close();
                }
            });
            controller.initData();

            stage.show();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void showAndroid() {
        FXMLLoader dbdetailloader = new FXMLLoader(Application.class.getResource("../../../fxml/OptionAndroid.fxml"));
        try {
            dbdetailloader.load();
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }
        Parent root = dbdetailloader.getRoot();
        OptionAndroidController controller = dbdetailloader.getController();
        controller.getCancel().setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                stopWait();
            }
        });
        controller.getOk().setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                ProjectManager dBmanger = ManagerFactory.getProjectManager();
                Dialog.showDirectoryChooser(dBmanger.getPath(), new Dialog.DirectoryCall() {
                    @Override
                    public void call(File result) {
                        System.out.println("生成目录:" + result.getAbsolutePath());
                        AndroidOption androidOption = new AndroidOption();
                        androidOption.projectName = controller.getName().getText();
                        androidOption.packages = controller.getPackages().getText();
                        androidOption.domain = controller.getDomain().getText();
                        dBmanger.generate(result.getAbsolutePath(), androidOption);
                    }
                });
            }
        });

        popup = new Stage();
        popup.initModality(Modality.APPLICATION_MODAL);

        Scene scene = new Scene(root);

        popup.setOnCloseRequest(new EventHandler<WindowEvent>() {
            @Override
            public void handle(WindowEvent event) {
                stopWait();
            }
        });
        popup.setScene(scene);
        popup.setTitle("配置");
        popup.show();
    }

    public static void showVue() {
        FXMLLoader dbdetailloader = new FXMLLoader(Application.class.getResource("../../../fxml/OptionVue.fxml"));
        try {
            dbdetailloader.load();
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }
        Parent root = dbdetailloader.getRoot();
        OptionVueController controller = dbdetailloader.getController();
        controller.getCancel().setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                stopWait();
            }
        });
        controller.getOk().setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                ProjectManager dBmanger = ManagerFactory.getProjectManager();
                Dialog.showDirectoryChooser(null, new Dialog.DirectoryCall() {
                    @Override
                    public void call(File result) {
                        System.out.println("生成目录:" + result.getAbsolutePath());
                        VueOption vueOption = new VueOption();
                        ToggleGroup type = controller.getType();
                        RadioButton value = (RadioButton) type.selectedToggleProperty().getValue();
                        vueOption.type = value.textProperty().getValue();
                        dBmanger.generate(result.getAbsolutePath(), vueOption);
                    }
                });
            }
        });

        popup = new Stage();
        popup.initModality(Modality.APPLICATION_MODAL);

        Scene scene = new Scene(root);

        popup.setOnCloseRequest(new EventHandler<WindowEvent>() {
            @Override
            public void handle(WindowEvent event) {
                stopWait();
            }
        });
        popup.setScene(scene);
        popup.setTitle("配置");
        popup.show();
    }

    public static void showInput(String title, String hint, InputCall inputCall) {
        TextInputDialog dialog = new TextInputDialog();
        dialog.setTitle(title);
        dialog.setHeaderText(null);
        dialog.setContentText(hint);
        dialog.setX(JavaFxApplication.primaryStage.getX() + JavaFxApplication.primaryStage.getWidth() / 2 - 140);
        dialog.setY(JavaFxApplication.primaryStage.getY() + JavaFxApplication.primaryStage.getHeight() / 2 - 70);
        Optional<String> result = dialog.showAndWait();
        if (result.isPresent()) {
            inputCall.call(result.get());
        }
    }

    public static void showMethodInput(String title, String hint, InputMethodCall inputCall) {
        javafx.scene.control.Dialog dialog = new javafx.scene.control.Dialog();

        dialog.setTitle(title);
        dialog.getDialogPane().getButtonTypes().addAll(ButtonType.OK, ButtonType.CANCEL);
        dialog.setX(JavaFxApplication.primaryStage.getX() + JavaFxApplication.primaryStage.getWidth() / 2 - 115);
        dialog.setY(JavaFxApplication.primaryStage.getY() + JavaFxApplication.primaryStage.getHeight() / 2 - 70);
        GridPane gridPane = new GridPane();
        gridPane.setHgap(10);
        gridPane.setVgap(10);
        gridPane.setPadding(new Insets(10, 10, 10, 10));
        dialog.getDialogPane().setContent(gridPane);

        TextField nameField = new TextField();
        nameField.setPromptText("请输入业务名称");
        TextField noteField = new TextField();
        noteField.setPromptText("请输入业务注释");

        gridPane.add(new Label("业务名称:"), 0, 0);
        gridPane.add(nameField, 1, 0);
        gridPane.add(new Label("业务注释:"), 0, 1);
        gridPane.add(noteField, 1, 1);

        Optional<ButtonType> optional = dialog.showAndWait();
        if (optional.isPresent() && optional.get() == ButtonType.OK) {
            String name = nameField.getText();
            String note = noteField.getText();
            if (StringUtil.isEmpty(name)) {
                Dialog.showYesNo("业务方法不能为空");
            } else if (inputCall != null) {
                inputCall.call(name, note);
            }
        }
    }

    private static void check(OptionApiController controller, boolean check, String key) {
        for (Api api : controller.getData()) {
            if (api.getMethod().contains(key)) {
                api.setCheck(check);
            }
        }
        controller.initData();
    }

    public interface InputCall {
        void call(String input);
    }

    public interface InputMethodCall {
        void call(String name, String note);
    }

    public interface ConfirmCall {
        void call(boolean result);
    }

    public interface DirectoryCall {
        void call(File result);
    }

    private static File findAction(File file) {
        if (file == null) {
            return null;
        } else if (Tool.hasChild(file, "action") && Tool.hasChild(file, "module")) {
            return file;
        }

        if (file.listFiles() != null) {
            for (File f : file.listFiles()) {
                File modul = findAction(f);
                if (modul != null) {
                    return modul;
                }
            }
        }

        return null;
    }
}
